<template>
  <div id='commodity_recycle'>
    <div class="search-box">
      <Row type="flex">
        <Row type="flex" justify="start" class="search-item-left">
          <Col class="search-item"><span class="search-label">输入搜索：</span><Input placeholder="商品名称/商品编码/条形码" v-model='searchName'></Input></Col>
          <Col class="search-item" style="display: flex;align-items: center;">
            <span class="search-label">商品分类：</span>
            <!-- <Select v-model="searchObj.classify" style="width:200px" @on-change="search">
              <OptionGroup :label="ele.categoryName" v-for="(ele, idx) in classifyList" :key='idx'>
                <Option v-for="item in ele.subCategoryList" :value="item.categoryId" :key="item.categoryId">{{ item.categoryName }}</Option>
              </OptionGroup>
            </Select> -->
            <vueTreeselectChoice :width="200" v-model="searchObj.classify" :disable-branch-nodes="true"  @input="search"  :options="classifyList" permissionCode='1'></vueTreeselectChoice>
          </Col>
          <Col class="search-item">
            <span class="search-label">所属类型：</span>
            <Select v-model="searchObj.type" @on-change="search" style="width:180px" placeholder='请选择'>
              <Option v-for="item in typeList" :value="item.typeCode" :key="item.value">{{ item.typeName }}</Option>
            </Select>
          </Col>
          <Col class="search-item">
            <Button class="search-btn" type='primary' @click="doSearch">查询</Button>
          </Col>
          <Col class="search-item">
            <Button class="search-btn" @click="reset">重置</Button>
          </Col>
        </Row>
      </Row>
    </div>
    <Table stripe class="table-list" :columns="columns" :data="tableData" :loading="loading" :height="tableHeight" ref="selection" @on-selection-change='selectItem' @on-sort-change='changeSort'>
      <template slot-scope="{ row }" slot="thumbnail">
        <div>
          <img :src="row.thumbnail?row.thumbnail:defaultUrl" alt="" style="width: 90px;height: 60px;display: block;margin: 15px 0;">
        </div>
      </template>
      <template slot-scope="{ row }" slot="goodsKind">
        <span v-if="row.goodsKindList">{{row.goodsKindList[0].typeName}}</span>
      </template>
      <template slot-scope="{ row }" slot="classify">
        <span v-if='row.parentCategoryName || row.categoryName'>{{row.parentCategoryName}}>{{row.categoryName}}</span>
      </template>
      <template slot-scope="{ row }" slot="action">
        <i class="iconsys icondetail" title="查看" @click='skipDetail(row)' v-if="hasPermission('moms:product:detail')"></i>
        <Poptip confirm title="你确定要还原吗？" transfer @on-ok="restore(row)" style="text-align:left" >
          <i class="iconsys iconhuanyuan" title="还原" v-if="hasPermission('moms:product:revert')"></i>
        </Poptip>
      </template>
    </Table>
    <Row type='flex' justify="space-between">
      <Col span="12" class="module-menu-nav">
        <Button class="module-menu-margin" @click="handleSelectAll">{{btnTitle}}</Button>
        <Dropdown placement="top" @on-click='batchAll'>
          <Button class="check_all">批量操作</Button>
          <DropdownMenu slot="list" style="text-align:center">
            <DropdownItem name='1' v-if="hasPermission('moms:product:revert')">批量还原</DropdownItem>
            <!-- <DropdownItem name='2'>批量删除</DropdownItem> -->
          </DropdownMenu>
        </Dropdown>
      </Col>
      <Col span="12">
        <div class="page-box">
            <Page :total="pageObj.total"
            :page-size='pageObj.pageSize'
            :current='pageObj.pageIndex'
            :page-size-opts='[20,50,100,200]'
            show-total
            show-sizer
            @on-change='changePageIndex'
            @on-page-size-change='changePageSize' />
        </div>
      </Col>
    </Row>
  </div>
</template>

<script>
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import { getRecycleList, productRecover, kindList, getClassifyList } from '@/api/commondity/index'
export default {
  name: 'commodity_recycle',
  computed: {
    tableHeight () {
      let height = this.tableData.length > 6 ? 580 : 0
      return height
    }
  },
  components: { vueTreeselectChoice },
  watch: {
    selectArrry (val) {
      if (val.length === this.tableData.length && this.tableData.length !== 0) {
        this.btnTitle = '取消全选'
        this.allStatus = false
      } else {
        this.btnTitle = '全选'
        this.allStatus = true
      }
    },
    '$route' (newRoute) {
      if (newRoute.name === 'commodity_recycle') {
        this.getData()
      }
    }
  },
  data () {
    return {
      defaultUrl: require('@/assets/images/default.png'),
      btnTitle: '全选',
      allStatus: true, // 全选状态
      selectArrry: [],
      sortBy: 'desc',
      loading: false,
      searchName: '',
      searchObj: {
        searchName: '',
        classify: null,
        type: ''
      },
      pageObj: {
        total: 0,
        pageIndex: 1,
        pageSize: 20
      },
      classifyList: [],
      typeList: [],
      tableData: [],
      columns: [
        {
          type: 'selection',
          width: 60
        },
        {
          title: '商品编码',
          key: 'skuId',
          sortable: 'custom'
        },
        {
          title: '商品主图',
          slot: 'thumbnail'
        },
        {
          title: '商品名称',
          key: 'skuName'
        },
        {
          title: '商品分类',
          slot: 'classify'
        },
        {
          title: '所属类型',
          slot: 'goodsKind'
        },
        {
          title: '条码',
          key: 'barcode'
        }
        // {
        //   title: '操作',
        //   slot: 'action',
        //   width: 180
        // }
      ]
    }
  },
  methods: {
    changeSort (column, key, order) {
      this.sortBy = column.order
      this.getData()
    },
    search () {
      this.pageObj.pageIndex = 1
      this.getData()
    },
    doSearch () {
      this.searchObj.searchName = this.searchName
      this.pageObj.pageIndex = 1
      this.getData()
    },
    reset () {
      this.searchName = ''
      this.searchObj = {
        searchName: '',
        classify: null,
        type: ''
      }
      this.pageObj.pageIndex = 1
      this.pageObj.pageSize = 20
      this.getData()
    },
    skipDetail (row) {
      this.$router.push({ name: 'commodity_detail', params: { id: row.skuId } })
    },
    // 还原接口
    recover (data) {
      productRecover(data).then(res => {
        if (res.data.status === 200) {
          if (data.skuId.length > 1) {
            this.$Message.success('批量还原成功!')
            this.getData()
            this.selectArrry = []
          } else {
            this.$Message.success('还原成功!')
            this.getData()
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    // 批量操作
    batchAll (val) {
      if (this.selectArrry.length > 0) {
        if (val === '1') {
          let arr = []
          this.selectArrry.forEach(item => {
            arr.push(item.skuId)
          })
          let data = {
            merchantId: this.$store.state.user.merchantId,
            skuId: arr,
            updater: this.$store.state.user.userId,
            updaterName: this.$store.state.user.userName
          }
          this.recover(data)
        }
      } else {
        this.$Message.error('请至少选择一项操作')
      }
    },
    restore (row) {
      let data = {
        merchantId: this.$store.state.user.merchantId,
        skuId: [row.skuId],
        updater: this.$store.state.user.userId,
        updaterName: this.$store.state.user.userName
      }
      this.recover(data)
    },
    changePageIndex (index) {
      this.pageObj.pageIndex = index
      this.getData()
    },
    changePageSize (size) {
      this.pageObj.pageSize = size
      this.pageObj.pageIndex = 1
      this.getData()
    },
    handleSelectAll () {
      this.$refs.selection.selectAll(this.allStatus)
    },
    selectItem (val) {
      this.selectArrry = val
    },
    // 获取商品分类
    getProductList () {
      function fliterItem (item) {
        if (!item) return null
        item.id = item.categoryId
        item.orgName = item.categoryName
        if (item.subCategoryList && item.subCategoryList.length) {
          item.childList = item.subCategoryList.map(ele => {
            let newImte = fliterItem(ele)
            return newImte
          })
        }
        return item
      }
      getClassifyList({
        merchantId: this.$store.state.user.merchantId
      }).then(res => {
        if (res.data.status === 200) {
          this.classifyList = (res.data.data.categories || []).map(item => {
            let newImte = fliterItem(item)
            return newImte
          })
        }
      })
    },
    // 获取所属分类
    getkindList () {
      kindList({
        merchantId: this.$store.state.user.merchantId,
        level: 1
      }).then(res => {
        if (res.data.status === 200) {
          this.typeList = res.data.data
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    getData () {
      this.loading = true
      getRecycleList({
        merchantId: this.$store.state.user.merchantId,
        categoryId: this.searchObj.classify,
        keyword: this.searchObj.searchName,
        goodsKind: this.searchObj.type,
        offset: this.pageObj.pageSize * (this.pageObj.pageIndex - 1),
        limit: this.pageObj.pageSize,
        sortBy: this.sortBy
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.selectArrry = []
          this.tableData = result.data.goods || []
          this.pageObj.total = result.data.total
          if (result.data.goods.length / this.pageObj.pageSize === 0) {
            if (this.pageObj.pageIndex > 1) {
              this.pageObj.pageIndex--
              this.getData()
            }
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.loading = false
        this.$Message.error(`${err}`)
      })
    }
  },
  mounted () {
    this.getProductList()
    this.getkindList()
    this.getData()
    if (this.hasPermission(['moms:product:detail', 'moms:product:revert'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        width: 200
      })
    }
  }
}
</script>
